from fund.strategy.strategy_util import process_dates


# 定投
def daily_invest(df, money=100, start_date=None, end_date=None):
    start_date, end_date = process_dates(df, start_date, end_date)
    total_cost = 0
    total_units = 0
    daily_investment = money

    # 筛选日期范围内的数据
    df_range = df[(df.index >= start_date) & (df.index <= end_date)]

    # 遍历有效数据
    for index, row in df_range.iterrows():
        net_value = row['单位净值']
        if net_value <= 0:
            continue  # 跳过无效净值
        daily_units = daily_investment / net_value
        total_units += daily_units
        total_cost += daily_investment

    # 计算最终资产
    if not df_range.empty:
        last_net_value = df_range['单位净值'].iloc[-1]
        final_asset = total_units * last_net_value
        buy_times = len(df_range)  # 实际买入天数
    else:
        final_asset = 0
        last_net_value = 0
        buy_times = 0

    # 计算收益指标
    total_profit = final_asset - total_cost
    total_return_rate = total_profit / total_cost if total_cost != 0 else 0
    investment_days = (end_date - start_date).days

    # 年化收益率（保持原有公式）
    if total_cost != 0 and investment_days > 0:
        annual_return_rate = (final_asset / total_cost) ** (365 / investment_days) - 1
    else:
        annual_return_rate = 0

    return {
        "开始时间": start_date.strftime('%Y-%m-%d'),
        "结束时间": end_date.strftime('%Y-%m-%d'),
        "总投入": total_cost,
        "最终资产": final_asset,
        "总利润": total_profit,
        "总收益率": total_return_rate,
        "年化收益率": annual_return_rate,
        "买入次数": buy_times,
        "买入记录": []
    }